package com.cheung.leetcode.tree;

import lyroot.entity.TreeNode;
import org.junit.jupiter.api.Test;

import java.util.List;

/**
 * @BelongsProject : java-leetcode
 * @BelongsPackage : com.cheung.leetcode.tree
 * @Author :  cheungming
 * @CreateTime : 2024-05-19 08:17:19
 * @Description : 二叉树层平均值
 * @Version : 1.0
 */
public class Code637Test {


    public List<Double> averageOfLevels(TreeNode root) {
        List<Double> list = new java.util.ArrayList<>();
        if (root == null) {
            return list;
        }
        java.util.Queue<TreeNode> queue = new java.util.LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            double sum = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                sum += node.val;
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
            }
            list.add(sum / size);
        }

        return list;
    }


    @Test
    public void test1() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        List<Double> list = averageOfLevels(root);
        // [3.00000,14.50000,11.00000]
        System.out.println(list);
    }


    @Test
    public void test2() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.left.left = new TreeNode(15);
        root.left.right = new TreeNode(7);
        List<Double> list = averageOfLevels(root);
        // [3.00000,14.50000,11.00000]
        System.out.println(list);
    }
}


